package net.lab1024.sa.admin.module.users.consumablesinventory.service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

import net.lab1024.sa.admin.module.fabricmaterials.dao.FabricMaterialsDao;
import net.lab1024.sa.admin.module.fabricmaterials.domain.entity.FabricMaterialsEntity;
import net.lab1024.sa.admin.module.fabricmaterials.domain.vo.FabricMaterialsVO;
import net.lab1024.sa.admin.module.users.consumablesinventory.dao.ConsumablesInventoryDao;
import net.lab1024.sa.admin.module.users.consumablesinventory.domain.entity.ConsumablesInventoryEntity;
import net.lab1024.sa.admin.module.users.consumablesinventory.domain.form.ConsumablesInventoryAddForm;
import net.lab1024.sa.admin.module.users.consumablesinventory.domain.form.ConsumablesInventoryQueryForm;
import net.lab1024.sa.admin.module.users.consumablesinventory.domain.form.ConsumablesInventoryUpdateForm;
import net.lab1024.sa.admin.module.users.consumablesinventory.domain.form.AcceptFrom;
import net.lab1024.sa.admin.module.users.consumablesinventory.domain.vo.ConsumablesInventoryVO;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 实训室耗材入库 Service
 *
 * @Author xixi
 * @Date 2024-11-08 13:31:03
 * @Copyright 🐂🐎bloc
 */

@Service
public class ConsumablesInventoryService {
    private static final int STATUS_ACCEPT = 1;

    @Resource
    private ConsumablesInventoryDao consumablesInventoryDao;

    @Resource
    private FabricMaterialsDao fabricMaterialsDao;

    /**
     * 分页查询
     *
     * @param queryForm
     * @return
     */
    public PageResult<ConsumablesInventoryVO> queryPage(ConsumablesInventoryQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<ConsumablesInventoryVO> list = consumablesInventoryDao.queryPage(page, queryForm);
        PageResult<ConsumablesInventoryVO> pageResult = SmartPageUtil.convert2PageResult(page, list);
        return pageResult;
    }

    /**
     * 添加
     */
    public ResponseDTO<String> add(ConsumablesInventoryAddForm addForm) {
        ConsumablesInventoryEntity consumablesInventoryEntity = SmartBeanUtil.copy(addForm, ConsumablesInventoryEntity.class);
        consumablesInventoryDao.insert(consumablesInventoryEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     *
     * @param updateForm
     * @return
     */
    public ResponseDTO<String> update(ConsumablesInventoryUpdateForm updateForm) {
        ConsumablesInventoryEntity consumablesInventoryEntity = SmartBeanUtil.copy(updateForm, ConsumablesInventoryEntity.class);
        consumablesInventoryDao.updateById(consumablesInventoryEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     *
     * @param idList
     * @return
     */
    public ResponseDTO<String> batchDelete(List<Integer> idList) {
        if (CollectionUtils.isEmpty(idList)){
            return ResponseDTO.ok();
        }

        consumablesInventoryDao.deleteBatchIds(idList);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    public ResponseDTO<String> delete(Integer id) {
        if (null == id){
            return ResponseDTO.ok();
        }

        consumablesInventoryDao.deleteById(id);
        return ResponseDTO.ok();
    }
    /**
     * 验收 @Author lyy
     */
    public ResponseDTO<String> accept(AcceptFrom acceptFrom) {
        // 复制属性
        ConsumablesInventoryEntity inventoryEntity = SmartBeanUtil.copy(acceptFrom, ConsumablesInventoryEntity.class);
        ConsumablesInventoryEntity updateEntity = new ConsumablesInventoryEntity();
        updateEntity.setId(inventoryEntity.getId());
        updateEntity.setStatus(inventoryEntity.getStatus());
        updateEntity.setInspector(inventoryEntity.getInspector());
        updateEntity.setWarehouseManager(inventoryEntity.getWarehouseManager());

        // 如果状态为 "已验收"
        if (STATUS_ACCEPT == updateEntity.getStatus()) {
            // 设置入库日期
            LocalDateTime now = LocalDateTime.now();
            updateEntity.setEntryDate(Timestamp.valueOf(now));

            // 检查是否存在相同代码的商品
            FabricMaterialsVO existingMaterial = queryByCode(inventoryEntity.getMaterialCode());
            if (existingMaterial != null) {
                // 存在商品，更新库存
                updateExistingMaterial(existingMaterial, inventoryEntity.getPurchaseQuantity(),inventoryEntity.getWarehouseManager());
            } else {
                // 不存在商品，创建新商品
                createNewMaterial(inventoryEntity);
            }
        }

        // 更新消耗品库存状态
        consumablesInventoryDao.updateById(updateEntity);

        return ResponseDTO.ok();
    }

    private void updateExistingMaterial(FabricMaterialsVO existingMaterial, int purchaseQuantity,int manager) {
        FabricMaterialsEntity fabricMaterialsEntity = new FabricMaterialsEntity();
        fabricMaterialsEntity.setId(existingMaterial.getId());
        fabricMaterialsEntity.setInStock(existingMaterial.getInStock() + purchaseQuantity);
        fabricMaterialsEntity.setQuantity(existingMaterial.getQuantity() + purchaseQuantity);
        fabricMaterialsEntity.setManager(manager);
        fabricMaterialsDao.updateById(fabricMaterialsEntity);
    }

    private void createNewMaterial(ConsumablesInventoryEntity inventoryEntity) {
        FabricMaterialsEntity newMaterial = new FabricMaterialsEntity();
        newMaterial.setFabricMaterialCode(inventoryEntity.getMaterialCode());
        newMaterial.setFabricMaterialName(inventoryEntity.getMaterialName());
        newMaterial.setFabicMaterialCategory(inventoryEntity.getCategory());
        newMaterial.setSpecModel(inventoryEntity.getSpecificationModel());
        newMaterial.setUnitPrice(inventoryEntity.getUnitPrice());
        newMaterial.setTotalPrice(inventoryEntity.getTotalPrice());
        newMaterial.setQuantity(inventoryEntity.getPurchaseQuantity());
        newMaterial.setPurchaseWay(inventoryEntity.getPurchaseChannel());
        newMaterial.setStorageLocation(inventoryEntity.getStorageLocation());
        newMaterial.setManager(inventoryEntity.getWarehouseManager());
        newMaterial.setInStock(inventoryEntity.getPurchaseQuantity());
        fabricMaterialsDao.insert(newMaterial);
    }

    public FabricMaterialsVO queryByCode(String code) {
        // 查询是否存在该商品代码
        String codeCount = fabricMaterialsDao.queryFabricMaterialCode(code);
        if ("1".equals(codeCount)) {
            return fabricMaterialsDao.getFabricMaterials(code);
        }
        return null;
    }




}
